import { ref } from 'vue'
import { defineStore } from 'pinia'

import { getUserInfo } from '@/api/user'
import type { UserInfo } from '@/types/user'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref<string>()

    const userInfo = ref<UserInfo>({})

    // 设置token
    const setToken = (value: string) => (token.value = value)

    // 设置用户信息
    const setUserInfo = (value: UserInfo) => (userInfo.value = value)

    // 更新
    const update = async () => {
      const userInfo = await getUserInfo()
      setUserInfo(userInfo)
    }

    // 重置
    const reset = () => {
      token.value = void 0
      userInfo.value = {}
    }

    return { token, userInfo, setToken, setUserInfo, update, reset }
  },
  { persist: true }
)
